﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Xml;
using Microsoft.VisualStudio.TestTools.Diagnostics;

namespace RowCountDataCollector
{
    /// Read name/value configurations from the XML element and save them in a dictionary
    public class CollectorConfigurationManager
    {
        // Configuration XML constants
        private const string SettingNodeName = "Setting";
        private const string SettingNameAttributeName = "name";
        private const string SettingValueAttributeName = "value";
        private Dictionary<string, string> m_nameValuePairs = new Dictionary<string, string>();

        [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode")]
        public CollectorConfigurationManager(XmlElement configurationElement)
        {
            if (configurationElement == null)
            {
                return;
            }

            // Load settings into a dictionary
            foreach (XmlNode settingNode in configurationElement.ChildNodes)
            {
                XmlElement settingElement = settingNode as XmlElement;
                if (settingElement == null)
                {
                    continue;
                }

                // Get the setting name
                string settingName = settingElement.GetAttribute(SettingNameAttributeName);
                if (string.IsNullOrEmpty(settingName))
                {
                    continue;
                }

                // Get the setting value
                string settingValue = settingElement.GetAttribute(SettingValueAttributeName);
                m_nameValuePairs[settingName] = settingValue;
            }
        }

        public string this[string name]
        {
            get
            {
                if (name == null)
                {
                    return null;
                }

                string settingValue;
                m_nameValuePairs.TryGetValue(name, out settingValue);
                return settingValue;
            }
            set
            {
                m_nameValuePairs[name] = value;
            }
        }
    }
}
